package org.linlinjava.litemall.mechanismadmin.web;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeOrderSettleRequest;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipayTradeOrderSettleResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.config.AES;
import org.linlinjava.litemall.core.util.JacksonUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.core.util.bcrypt.BCryptPasswordEncoder;
import org.linlinjava.litemall.db.domain.LitemallMechanism;
import org.linlinjava.litemall.db.domain.LitemallMechanismCategory;
import org.linlinjava.litemall.db.domain.LitemallMechanismUser;
import org.linlinjava.litemall.db.domain.ProxyIntroduce;
import org.linlinjava.litemall.db.service.LitemallMechanismCategoryService;
import org.linlinjava.litemall.db.service.LitemallMechanismService;
import org.linlinjava.litemall.db.service.LitemallMechanismUserService;
import org.linlinjava.litemall.db.service.LitemallProxyService;
import org.linlinjava.litemall.mechanismadmin.annotation.LoginAdmin;
import org.linlinjava.litemall.mechanismadmin.dao.AdminToken;
import org.linlinjava.litemall.mechanismadmin.service.AdminTokenManager;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/mechanismadmin/login")
public class MechanismAdminAuthController {
    private final Log logger = LogFactory.getLog(MechanismAdminAuthController.class);

    private LitemallMechanismUserService mechanismUserService;

    private LitemallMechanismService litemallMechanismService;

    private LitemallProxyService litemallProxyService;

    private LitemallMechanismCategoryService mechanismCategoryService;

    public MechanismAdminAuthController(
        LitemallMechanismUserService mechanismUserService, LitemallMechanismService litemallMechanismService, LitemallProxyService litemallProxyService,LitemallMechanismCategoryService litemallMechanismCategoryService) {
        this.mechanismUserService = mechanismUserService;
        this.litemallMechanismService = litemallMechanismService;
        this.litemallProxyService = litemallProxyService;
        this.mechanismCategoryService = litemallMechanismCategoryService;
    }

    /**
     *  { username : value, password : value }
     */
    @PostMapping("/login")
    public Object login(@RequestBody String body){
        String username = JacksonUtil.parseString(body, "username");
        String password = JacksonUtil.parseString(body, "password");

        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            return ResponseUtil.badArgument();
        }

        List<LitemallMechanismUser> mechanismUserList = mechanismUserService.queryByUsername(username);
        Assert.state(mechanismUserList.size() < 2, "同一个用户名存在两个账户");
        if(mechanismUserList.size() == 0){
            return ResponseUtil.fail(403, "用户名称不对");
        }
        LitemallMechanismUser mechanismUser = mechanismUserList.get(0);

        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if(!encoder.matches(password, mechanismUser.getPassword())){
            return ResponseUtil.fail(403, "账号密码不对");
        }
        //查看机构是否到期
        Integer mechanismId = mechanismUser.getMechanismId();
        LitemallMechanism litemallMechanism =litemallMechanismService.findById(mechanismId);
        if(litemallMechanism.getDeleted()){
            return ResponseUtil.fail(403, "机构使用权已到期，请联系爱能续费");
        }
        Integer adminId = mechanismUser.getId();
        // token
        AdminToken adminToken = AdminTokenManager.generateToken(adminId);

        return ResponseUtil.ok(adminToken.getToken());
    }

    /**
     *登出
     */
    @PostMapping("/logout")
    public Object login(@LoginAdmin Integer adminId){
        if(adminId == null){
            return ResponseUtil.unlogin();
        }

        return ResponseUtil.ok();
    }

    @GetMapping("/list")
    public Object list(
        String name,
        @RequestParam(value = "page", defaultValue = "1") Integer page,
        @RequestParam(value = "limit", defaultValue = "10") Integer limit){
        List<ProxyIntroduce> categoryList = litemallProxyService.querySelective( name, page, limit);

        Map<String, Object> data = new HashMap<>(16);
        data.put("items", categoryList);
        return ResponseUtil.ok(data);
    }


    @GetMapping("/category")
    public Object cates(){
        Map<String, Object> data = new HashMap<>();
        List<LitemallMechanismCategory> mcategory =  mechanismCategoryService.selectAll();
        List<Map<String, Object>> brandList = new ArrayList<>(mcategory.size());
        for(LitemallMechanismCategory brand : mcategory){
            Map<String, Object> b = new HashMap<>(2);
            b.put("value", brand.getId());
            b.put("label", brand.getName());
            brandList.add(b);
        }
        data.put("mcategory",mcategory);
        data.put("brandList",brandList);

        return  ResponseUtil.ok(data);
    }

}
